package cn.minimelon.bittermelon.solon;

import cn.minimelon.bittermelon.bean.LoginUser;
import cn.minimelon.bittermelon.exception.WebException;
import cn.minimelon.bittermelon.utils.Melon;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Render;
import org.noear.solon.core.handle.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 所有请求基类，统一异常处理
 *
 * @author hiro 2021-11-20 created
 */
public class BaseController implements Render {
    protected final static Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Override
    public void render(Object obj, Context ctx) throws Throwable {
        if (ctx.getRendered()) {
            return;
        }

        // 如果是异常
        if (obj instanceof WebException) {
            WebException webException = (WebException) obj;
            ctx.status(500);
            ctx.render(Result.failure(webException.getExpCode()));
            logger.error(webException.getMessage());
        } else if (obj instanceof Exception) {
            Exception ex = (Exception) obj;
            ctx.status(500);
            ctx.render(ex.getMessage());
            logger.error(ex.getMessage());
        } else {
            ctx.render(obj);
        }
    }

    protected LoginUser getLoginUser() {
        return Context.current().attr(Melon.LOGIN_USER_SESSION);
    }
}
